/*
 * ResourceLoader.cpp
 *
 *  Created on: Aug 23, 2013
 *      Author: zapmunk
 */

#include "headerstop.h"

#include "ResourceLoader.h"

using std::vector;

#include "RESOURCES.h"

#define init(name, path, type) \
	type ## Resource ResourceLoader::name(path, CURRENTLOAD, #name);

#define CURRENTLOAD Resource::PRELOAD
RESOURCES_PRELOAD;
#undef CURRENTLOAD
#define CURRENTLOAD Resource::AUTOLOAD
RESOURCES_AUTOLOAD;
#undef CURRENTLOAD
#define CURRENTLOAD Resource::MANUAL
RESOURCES_MANUAL;

#undef init
#define init(name, path, type) \
	CURRENTVECTOR.push_back(&name);

void ResourceLoader::initResources() {
#define CURRENTVECTOR preload
	RESOURCES_PRELOAD;
#undef CURRENTVECTOR
#define CURRENTVECTOR autoload
	RESOURCES_AUTOLOAD;
#undef CURRENTVECTOR
#define CURRENTVECTOR manual
	RESOURCES_MANUAL;
#undef CURRENTVECTOR
}

vector<Resource*> ResourceLoader::preload;
vector<Resource*> ResourceLoader::autoload;
vector<Resource*> ResourceLoader::manual;

void ResourceLoader::loadAll(vector<Resource*>* resources, ProgressTracker* tracker) throw(LoadException) {
	//TODO: manage tracker
	for (vector<Resource*>::iterator i = resources->begin(); i != resources->end(); ++i) {
		Resource* r = *i;
		if (!r->isLoaded()) {
			if (!r->load()) throw LoadException(r->getName(), r->getPath());
		}
	}
}

void ResourceLoader::unloadAll() {
	for (vector<Resource*>::iterator i = preload.begin(); i != preload.end(); ++i) {
		Resource* r = *i;
		if (r->isLoaded()) {
			r->unload();
		}
	}
	for (vector<Resource*>::iterator i = autoload.begin(); i != autoload.end(); ++i) {
		Resource* r = *i;
		if (r->isLoaded()) {
			r->unload();
		}
	}
	for (vector<Resource*>::iterator i = manual.begin(); i != manual.end(); ++i) {
		Resource* r = *i;
		if (r->isLoaded()) {
			r->unload();
		}
	}
}

#undef RESOURCES_PRELOAD
#undef RESOURCES_AUTOLOAD
#undef RESOURCES_MANUAL
#undef init
